import { defineStore } from 'pinia';
import { ref, computed, shallowRef } from 'vue';
import {
  fetchGanttData,
  saveBlogPost,
  updateBlogPost,
  updatePostTimeline,
  createMilestone,
  createDependency,
  deleteDependency,
  getMilestones,
  getDependencies
} from '@/api/gantt';
import { getCollectionsByUser } from '@/api/collection';
import type { BlogPost, PostDependency, PostMilestone, Topic } from '@/components/GanttChart/types';
// 引入模拟数据
import { mockBlogPosts, mockMilestones, mockDependencies, mockTopics } from '@/mock/gantt';
import GSTC, { GSTCResult, Config, Items, Columns } from 'gantt-schedule-timeline-calendar';
import { useDebounceFn } from '@vueuse/core';
import dayjs from 'dayjs';
import { s } from 'vite/dist/node/types.d-aGj9QkWt';
const GSTCID = GSTC.api.GSTCID;

/**
 * Gantt图表状态管理
 */
export const useGanttStore = defineStore('gantt', () => {
  // 深度响应式数据
  const gstc = ref<GSTCResult | null>(null);
  const posts = ref<BlogPost[]>([]);
  const dependencies = ref<PostDependency[]>([]);
  const milestones = ref<PostMilestone[]>([]);
  const topics = ref<Topic[]>([]);
  const zoomLevel = ref<'day' | 'week' | 'month'>('week');
  const creatingDependency = ref<string[]>([]);
  const isLoading = ref(false);
  const error = ref<string | null>(null);
  const showPostEditor = ref(false);
  const showMilestoneDialog = ref(false);
  const dateRange = ref<[string, string]>([
    new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
    new Date(Date.now() + 60 * 24 * 60 * 60 * 1000).toISOString()
  ]);
  const isShowDetail = ref(false);

  // 非深度响应式数据
  const activePostIds = shallowRef<string[]>([]);
  const activePosts = shallowRef<BlogPost[]>([]);

  const postStatusCount = computed(() => {
    const count: Record<string, number> = {};
    posts.value.forEach(post => {
      count[post.status] = (count[post.status] || 0) + 1;
    });
    return count;
  });

  const progressStats = computed(() => {
    const total = posts.value.length;
    const completed = posts.value.filter(p => p.progress === 100).length;
    return {
      total,
      completed,
      percentage: total > 0 ? Math.round((completed / total) * 100) : 0
    };
  });

  // 定义颜色数组，用于生成随机颜色
  const colors = ['#E74C3C', '#DA3C78', '#7E349D', '#0077C0', '#07ABA0', '#0EAC51', '#F1892D'];
  // 生成随机颜色的函数
  const getRandomColor = () => colors[Math.floor(Math.random() * colors.length)];

  // API 操作
  const fetchPosts = async (fromDate: Date, toDate: Date) => {
    isLoading.value = true;
    error.value = null;
    try {
      const startDate = fromDate ? fromDate : dayjs().subtract(1, 'month').toDate();
      const endDate = toDate ? toDate : dayjs().add(1, 'month').toDate();
      const { data } = await fetchGanttData({
        startDate: dayjs(startDate).format('YYYY-MM-DD'),
        endDate: dayjs(endDate).format('YYYY-MM-DD')
      });
      console.log('data', data);
      // posts.value = data.posts;
      // dependencies.value = data.dependencies;
      // milestones.value = data.milestones;

      // 使用模拟数据
      posts.value = mockBlogPosts.map(post => ({
        ...post,
        startTime: dayjs(post.startDate).valueOf(),
        endTime: dayjs(post.endDate).valueOf(),
        dependant: post.dependant?.map(id => GSTCID(id))
      }));
      console.log('posts前', posts.value);

      posts.value = data.posts.map(post => ({
        ...post,
        id: post.blogId,
        startTime: dayjs(post.startDate).valueOf(),
        endTime: dayjs(post.endDate).valueOf(),
        title: post.blogTitle,
        status: post.blogStatus,
        category: post.blogCategoryName,
        tags: post.blogTags,
        dependant: post.dependencies?.map(id => GSTCID(id))
      }));
      console.log('posts后', posts.value);
      dependencies.value = mockDependencies;
      console.log('dependencies前', dependencies.value);
      milestones.value = mockMilestones;
      console.log('milestones前', milestones.value);

      dependencies.value = data.dependencies;
      console.log('dependencies后', dependencies.value);
      milestones.value = mockMilestones;
      console.log('milestones后', milestones.value);

      // return {
      //   posts: mockBlogPosts,
      //   dependencies: mockDependencies,
      //   milestones: mockMilestones
      // };
    } catch (err) {
      error.value = 'Failed to fetch gantt data';
      console.error('Error fetching gantt data:', err);
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const createPost = async (postData: Omit<BlogPost, 'id'>) => {
    console.log('createPost', postData);
    isLoading.value = true;
    try {
      // const { data } = await saveBlogPost(postData);
      // posts.value.push(data);
      // return data;

      // 使用模拟数据
      const newPost = {
        ...postData,
        id: Math.random().toString(36).substr(2, 9),
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        progress: postData.progress || 0
      };
      posts.value.push(newPost);
      return newPost;
    } catch (err) {
      error.value = 'Failed to create post';
      console.error('Error creating post:', err);
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const updatePost = async (postData: Partial<BlogPost> & { id: string }) => {
    isLoading.value = true;
    try {
      // const { data } = await updateBlogPost(postData);
      // const index = posts.value.findIndex(p => p.id === postData.id);
      // if (index >= 0) {
      //   posts.value[index] = {
      //     ...posts.value[index],
      //     ...data
      //   };
      // }
      // return data;

      // 使用模拟数据
      const index = posts.value.findIndex(p => p.id === postData.id);
      if (index >= 0) {
        posts.value[index] = {
          ...posts.value[index],
          ...postData,
          updatedAt: new Date().toISOString()
        };
      }
      return posts.value[index];
    } catch (err) {
      error.value = 'Failed to update post';
      console.error('Error updating post:', err);
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const updatePostSchedule = async (
    updates: Array<{
      id: string;
      startDate: string;
      endDate: string;
    }>
  ) => {
    isLoading.value = true;
    try {
      // await updatePostTimeline(updates);
      updates.forEach(update => {
        const post = posts.value.find(p => p.id === update.id);
        if (post) {
          post.startDate = update.startDate;
          post.endDate = update.endDate;
        }
      });
    } catch (err) {
      error.value = 'Failed to update post schedule';
      console.error('Error updating post schedule:', err);
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  // 新增方法 - 单独获取里程碑
  const fetchMilestones = async () => {
    isLoading.value = true;
    error.value = null;
    try {
      // const { data } = await getMilestones();
      // milestones.value = data;
      // return data;

      // 使用模拟数据
      milestones.value = mockMilestones.map(milestone => ({
        ...milestone,
        date: milestone.date
      }));
      return mockMilestones;
    } catch (err) {
      error.value = 'Failed to fetch milestones';
      console.error('Error fetching milestones:', err);
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  // 新增方法 - 单独获取依赖关系
  const fetchDependencies = async () => {
    isLoading.value = true;
    error.value = null;
    try {
      // const { data } = await getDependencies();
      // dependencies.value = data;
      // return data;

      // 使用模拟数据
      dependencies.value = mockDependencies;
      return mockDependencies;
    } catch (err) {
      error.value = 'Failed to fetch dependencies';
      console.error('Error fetching dependencies:', err);
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const fetchTopics = async () => {
    isLoading.value = true;
    error.value = null;
    try {
      // 使用模拟数据
      topics.value = mockTopics;
      console.log('collection前', mockTopics);
      const { data } = await getCollectionsByUser();
      console.log('collection后', data);
      topics.value = data.map(item => ({
        id: item.id,
        name: item.name,
        priority: 0,
        progress: 0,
        startDate: item.createTime,
        endDate: item.createTime
      }));
      // return mockTopics;
    } catch (err) {
      error.value = 'Failed to fetch topics';
      console.error('Error fetching topics:', err);
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const saveMilestone = async (milestoneData: Omit<PostMilestone, 'id'>) => {
    isLoading.value = true;
    try {
      // const { data } = await createMilestone(milestoneData);
      // milestones.value.push(data);
      // return data;

      // 使用模拟数据
      const newMilestone = {
        ...milestoneData,
        id: Math.random().toString(36).substr(2, 9),
        createdAt: new Date().toISOString(),
        completed: milestoneData.completed || false
      };
      milestones.value.push(newMilestone);
      return newMilestone;
    } catch (err) {
      error.value = 'Failed to create milestone';
      console.error('Error creating milestone:', err);
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const saveDependency = async (dependencyData: Omit<PostDependency, 'id'>) => {
    console.log('Saving dependency:', dependencyData);
    isLoading.value = true;
    try {
      // const { data } = await createDependency(dependencyData);
      // dependencies.value.push(data);
      // creatingDependency.value = { sourceId: null };
      // return data;

      // 使用模拟数据
      const newDependency = {
        ...dependencyData,
        id: Math.random().toString(36).substr(2, 9),
        createdAt: new Date().toISOString()
      };
      dependencies.value.push(newDependency);
      creatingDependency.value = [];
      return newDependency;
    } catch (err) {
      error.value = 'Failed to create dependency';
      console.error('Error creating dependency:', err);
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const removeDependency = async (dependencyId: string) => {
    isLoading.value = true;
    try {
      // await deleteDependency(dependencyId);
      dependencies.value = dependencies.value.filter(dep => dep.id !== dependencyId);
      // 触发刷新甘特图
      window.dispatchEvent(new CustomEvent('gantt-dependency-removed'));
    } catch (err) {
      error.value = 'Failed to delete dependency';
      console.error('Error deleting dependency:', err);
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  // 通过useDebounceFn实现节流，避免频繁触发
  const setActivePosts = useDebounceFn((postIds: string[]) => {
    console.log('setActivePost', postIds);
    activePostIds.value = postIds;
    activePosts.value = posts.value.filter(item => postIds.includes(item.id));
  }, 500);

  const startDependencyCreation = (posts: BlogPost[]) => {
    if (!posts || !posts.length) return;
    creatingDependency.value = posts.map(item => item.id);
  };

  const cancelDependencyCreation = () => {
    creatingDependency.value = [];
  };

  const setZoomLevel = (level: 'day' | 'week' | 'month') => {
    zoomLevel.value = level;
  };

  const updateDateRange = (range: [string, string]) => {
    dateRange.value = range;
  };

  const setGstc = (_gstc: GSTCResult) => {
    gstc.value = _gstc;
  };

  const showDetailDialog = () => {
    isShowDetail.value = true;
  };

  const hideDetailDialog = () => {
    isShowDetail.value = false;
  };

  const reset = () => {
    posts.value = [];
    dependencies.value = [];
    milestones.value = [];
    activePostIds.value = [];
    creatingDependency.value = [];
    showPostEditor.value = false;
    showMilestoneDialog.value = false;
  };

  return {
    // 状态
    gstc,
    posts,
    topics,
    dependencies,
    milestones,
    zoomLevel,
    activePostIds,
    activePosts,
    creatingDependency,
    isLoading,
    error,
    showPostEditor,
    showMilestoneDialog,
    dateRange,
    isShowDetail,

    // 计算属性
    postStatusCount,
    progressStats,

    // 共通功能函数
    getRandomColor,

    // API 操作
    fetchPosts,
    createPost,
    updatePost,
    updatePostSchedule,
    fetchMilestones,
    fetchDependencies,
    fetchTopics,
    saveMilestone,
    saveDependency,
    removeDependency,

    // UI 操作
    setActivePosts,
    startDependencyCreation,
    cancelDependencyCreation,
    setZoomLevel,
    updateDateRange,
    reset,
    showDetailDialog,
    hideDetailDialog,

    // 全局状态
    setGstc
  };
});
